<?php
/**
 * Created by PhpStorm.
 * User: Tommy
 * Date: 2018/11/9
 * Time: 14:19
 */

namespace App\Services;


use App\Models\Hall;
use App\Models\User;
use App\Models\Agent;
use App\Models\ReportMoneyLog;
use App\Models\PartnerConfig;
use App\Models\ReportPartnerGame;
use common\utils\SysCode;
use Illuminate\Support\Facades\DB;

class ReportMoneyLogService
{
    const PARTNER_GAME_LIST = [
        '1' => '电子',
        '2' => '视讯',
        '3' => '体育',
        '4' => '电竞',
        '5' => '彩票',
        '6' => '棋牌',
    ];
    public static function getGameList(){
        $result = [];
        $rs = PartnerConfig::select('partner_id','partner_name','game_type')->get()->toArray();
        foreach ($rs as $v) {
            if(isset($result[$v['game_type']])){
                array_push($result[$v['game_type']]['list'],$v['partner_name']);
            }else{
                $result[$v['game_type']]['type'] = $v['game_type'];
                $result[$v['game_type']]['name'] = static::PARTNER_GAME_LIST[$v['game_type']];
                $result[$v['game_type']]['list'] = [$v['partner_name']];
            }
        }
        return array_values($result);
    }
    public static function getHallList(){
        return Hall::select('id as key','company_name as label')->get()->toArray();
    }
    //红包小费统计
    public static function getCashTipsList($params){
        $result = $where = $ids = [];
        $page = isset($params['page']) ? $params['page'] : 1;
        $size = isset($params['page_size']) ? $params['page_size'] : 20;
        $startTime = isset($params['date_begin']) ? $params['date_begin'] : date('Y-m-d', strtotime('-7 days'));
        $endTime = isset($params['date_end']) ? $params['date_end'] : date('Y-m-d');
        if(isset($params['name'])){
            if(!isset($params['hall_id']) || !isset($params['user_type'])){
                error_exit(SysCode::INVALID_ARGUMENT);
            }
            $ids = static::getUserIds($params['hall_id'],$params['user_type'],$params['name']);
            if(!$ids) return static::getEmptyData($page, $size);
        }
        $query = ReportPartnerGame::select('partner_name as name','partner_id',
            DB::raw("SUM(tips_amount) as tips_amount"),
            DB::raw("SUM(tips_times) as tips_times"),
            DB::raw("SUM(redbag_amount) as redbag_amount"),
            DB::raw("SUM(redbag_times) as redbag_times")
            );
        if(isset($params['hall_id'])) $where[] = ['hall_id','=' ,$params['hall_id']];
        if($startTime) $where[] = ['date', '>=', $startTime];
        if($endTime) $where[] = ['date', '<=', $endTime];
        if($ids) $query->whereIn('user_id', $ids);
        if(isset($params['game_ids']) && $params['game_ids']) $query->whereIn('partner_name', explode( ',', $params['game_ids']));
        $rs = $query->where($where)->groupBy('partner_name')->get()->toArray();
        if(!$rs) return static::getEmptyData($page, $size);
        $total = count($rs);
        $totalData = array_merge(['name'=>'总计'], [
            'tips_amount' => array_sum(array_column($rs,'tips_amount')),
            'tips_times' => array_sum(array_column($rs,'tips_times')),
            'redbag_amount' => array_sum(array_column($rs,'redbag_amount')),
            'redbag_times' => array_sum(array_column($rs,'redbag_times'))
            ]);
        //获取当前页数据
        // return $data;
        $index = 0;
        foreach ($rs as $items){
            if($index >= ($page-1)*$size && $index < $page*$size){
                array_push($result,$items);
            }
            $index++;
        }
        $pageData = array_merge(['name'=>'小计'], [
            'tips_amount' => array_sum(array_column($result,'tips_amount')),
            'tips_times' => array_sum(array_column($result,'tips_times')),
            'redbag_amount' => array_sum(array_column($result,'redbag_amount')),
            'redbag_times' => array_sum(array_column($result,'redbag_times'))
            ]);
        array_push($result, $pageData);
        array_push($result, $totalData);
        $date = str_replace('-', '/', $startTime).'-'.str_replace('-', '/', $endTime);
        foreach ($result as $k => &$v) {
            $v['date'] = $date;
        }
        return ['list' => $result, 'pagination' => ['page' => (int)$page, 'size' => (int)$size, 'count' => $total]];
    }
    /**
     * 获取出入款统计数据
     * @param int $id
     * @return array
     */
    public static function getCashTransferList($params)
    {
        $result = $where = $ids = [];
        $page = isset($params['page']) ? $params['page'] : 1;
        $size = isset($params['page_size']) ? $params['page_size'] : 20;
        if(isset($params['name'])){
            if(!isset($params['hall_id']) || !isset($params['user_type'])){
                error_exit(SysCode::INVALID_ARGUMENT);
            }
            $ids = static::getUserIds($params['hall_id'],$params['user_type'],$params['name']);
            if(!$ids) return static::getEmptyData($page, $size);
        }
        // $sqlKeys = static::getSqlKeys();
        // $preSelect ='';
        // foreach ($sqlKeys as $v) {
        //     $preSelect .= "sum({$v}) AS {$v},";
        // }
        // $query = ReportMoneyLog::selectRaw('date,' . $preSelect);
        // $query2 = ReportMoneyLog::selectRaw('date AS date,username AS username,' . $preSelect);
        $query = ReportMoneyLog::select('date',
            DB::raw('SUM(deposit_online_amount) as deposit_online_amount'),
            DB::raw('SUM(deposit_offline_amount) as deposit_offline_amount'),
            DB::raw('SUM(deposit_manual_amount) as deposit_manual_amount'),
            DB::raw('SUM(deposit_total_amount) as deposit_total_amount'),
            DB::raw('SUM(withdraw_online_amount) as withdraw_online_amount'),
            DB::raw('SUM(withdraw_manual_amount) as withdraw_manual_amount'),
            DB::raw('SUM(withdraw_fee_amount) as withdraw_fee_amount'),
            DB::raw('SUM(coupon_total_amount) as coupon_total_amount'),
            DB::raw('SUM(rebet_amount) as rebet_amount'),
            DB::raw('SUM(withdraw_refuse_amount) as withdraw_refuse_amount')
        );
        $query2 = ReportMoneyLog::select('date','username',
            DB::raw('SUM(deposit_online_amount) as deposit_online_amount'),
            DB::raw('SUM(deposit_offline_amount) as deposit_offline_amount'),
            DB::raw('SUM(deposit_manual_amount) as deposit_manual_amount'),
            DB::raw('SUM(deposit_total_amount) as deposit_total_amount'),
            DB::raw('SUM(withdraw_online_amount) as withdraw_online_amount'),
            DB::raw('SUM(withdraw_manual_amount) as withdraw_manual_amount'),
            DB::raw('SUM(withdraw_fee_amount) as withdraw_fee_amount'),
            DB::raw('SUM(coupon_total_amount) as coupon_total_amount'),
            DB::raw('SUM(rebet_amount) as rebet_amount'),
            DB::raw('SUM(withdraw_refuse_amount) as withdraw_refuse_amount')
        );
        $startTime = isset($params['date_begin']) ? date('Y-m-d 00:00:00', strtotime($params['date_begin'])) : null;
        $endTime = isset($params['date_end']) ? date('Y-m-d 23:59:59', strtotime($params['date_end'])) : null;
        if(isset($params['hall_id'])) $where[] = ['hall_id','=' ,$params['hall_id']];
        if ($startTime) $where[] = ['date', '>=', $startTime];
        if ($endTime) $where[] = ['date', '<=', $endTime];
        if($ids){
            $query->whereIn('user_id', $ids);
            $query2->whereIn('user_id', $ids);
        }
        $query->where($where)->groupBy('date');
        $total = $query->get()->count();
        if(!$total) return static::getEmptyData($page, $size);
        if(isset($params['sort_value']) && isset($params['sort_type'])){
            $orderBy = "{$params['sort_value']} {$params['sort_type']}";
        }else{
            $orderBy = 'date desc';
        }
        $query->orderBy('date','desc');
        //对人数去重获取具体数据
        $detailData = $query2->groupBy('date','username')->get()->toArray();
        //
        $data = $query->get()->toArray();
        foreach($data as &$datum){
            $datum['deposit_online_num'] = $datum['deposit_offline_num'] = $datum['deposit_manual_num'] = $datum['withdraw_manual_num'] = $datum['withdraw_fee_num'] = $datum['coupon_total_num'] = $datum['rebet_num'] = $datum['withdraw_refuse_num'] = 0;
            foreach($detailData as $v){
                if($datum['date'] == $v['date']){
                    if($v['deposit_online_amount']) $datum['deposit_online_num'] += 1;
                    if($v['deposit_offline_amount']) $datum['deposit_offline_num'] += 1;
                    if($v['deposit_manual_amount']) $datum['deposit_manual_num'] += 1;
                    if($v['withdraw_manual_amount']) $datum['withdraw_manual_num'] += 1;
                    if($v['withdraw_fee_amount']) $datum['withdraw_fee_num'] += 1;
                    if($v['coupon_total_amount']) $datum['coupon_total_num'] += 1;
                    if($v['rebet_amount']) $datum['rebet_num'] += 1;
                    if($v['withdraw_refuse_amount']) $datum['withdraw_refuse_num'] += 1;
                }
            }
        }
        $totalData = array_merge(['date'=>'总计'], static::getSumByData($data));
        //获取当前页数据
        // return $data;
        $index = 0;
        foreach ($data as $items){
            if($index >= ($page-1)*$size && $index < $page*$size){
                array_push($result,$items);
            }
            $index++;
        }
        $pageData = array_merge(['date'=>'小计'], static::getSumByData($result));
        array_push($result, $pageData);
        array_push($result, $totalData);
        //出入款差额（公司入款+在线充值+手动存款-会员出款-人工提出）
        //公司入款+在线充值+手动存款 = 总存款金额
        $transferDiffBalance = $totalData['deposit_total_amount'] - $totalData['withdraw_online_amount'] - $totalData['withdraw_manual_amount'];
        //赠送入款（返水 + 优惠）
        $sendBalance = $totalData['coupon_total_amount'] + $totalData['rebet_amount'];
        return ['list' => $result, 'pagination' => ['page' => (int)$page, 'size' => (int)$size, 'count' => $total, 'transfer_diff_balance' => $transferDiffBalance, 'send_balance' => $sendBalance]];
    }
    public static function getSumByData($data){
        $result = [];
        $keys = array_keys($data[0]);
        foreach($data as $v){
            foreach($keys as $key){
                if(is_numeric($v[$key]))
                    $result[$key] = (isset($result[$key]) ? $result[$key] : 0) + $v[$key];
            }
        }
        return $result;
    }
    public static function getEmptyData($page, $size){
        return [
            'pagination' => [
                'page' => (int)$page,
                'size' => (int)$size,
                'total' => 0,
            ],
            'list' => []
        ];
    }
    public static function getSqlKeys(){
        return ['deposit_online_amount','deposit_offline_amount','deposit_manual_amount','deposit_total_amount','withdraw_online_amount','withdraw_manual_amount','withdraw_fee_amount','coupon_total_amount','rebet_amount','withdraw_refuse_amount'];
    }
    /**
     * [根据用户用户名，代理名，股东名获取对应用户id]
     * @param  [type] $hallId   [厅主id]
     * @param  [type] $userType [用户类型]
     * @param  [type] $name     [用户名称]
     * @return [type]           [description]
     */
    public static function getUserIds($hallId, $userType, $name)
    {
        $idArr = [];
        if($userType == 'user'){
            $idArr = User::where('username', $name)->get()->toArray();
        }elseif($userType == 'agent'){
            $idArr = DB::table('agent as a')
            ->leftJoin('user as u','a.id','=','u.agent_id')
            ->select('u.id')
            ->where([['a.hall_id' ,'=', $hallId],['a.agent_name','=',$name]])
            ->get()->toArray();
        }elseif($userType == 'shareholder'){
            $shareholderId = Agent::where([['hall_id' ,'=', $hallId],['agent_name','=',$name]])->first();
            if($shareholderId){
                $idArr = DB::table('agent as a')
                ->leftJoin('user as u','a.id','=','u.agent_id')
                ->select(['a.id as agent_id','u.id'])
                ->where([['a.pid' ,'=', $shareholderId['id']]])
                ->get()->toArray();
            }
        }
        return array_filter(array_column($idArr,'id'));
    }
}